<template>
  <div style="height:100vh;overflow: hidden;
  background-image:linear-gradient(135deg,#f8c261,#f1efe1);">
    <el-container style="padding:30px;">
      <el-header>
        <el-row>
          <el-col :span="4">
            <span style="font-size: 30px;font-weight: bolder;font-family: 华文彩云;color: #fff;">吃了吗郑州分部</span>
          </el-col>
          <el-col :span="1">
            <img src="/imgs/login/verticalLine.png" style="height: 50px;width: 100%;">
          </el-col>
          <el-col :span="19">
            <span style="font-size: 30px;font-weight: bolder;font-family: 华文彩云;color: #fff;">线上餐厅管理系统</span>
          </el-col>
        </el-row>
      </el-header>

    </el-container>
      <div style="display:flex;align-items: center;justify-content: center;margin-top: 80px"><!--align-items: center：垂直居中；justify-content: center:横向居中-->
          <div style="display: flex;">
              <div style="flex: 1">
                  <img src="/imgs/login/img.png" style="width:400px;">
              </div>
              <div style="flex: 1">
                  <el-tabs   :stretch="true" type="border-card" v-model="activeName" style="height: 400px;width: 400px;box-sizing: border-box;border: none">
                      <el-tab-pane label="账号密码登录" name="first" >
                          <h3 style="text-align: center;">账号密码登录</h3>
                          <el-form label-position="top">
                              <el-form-item label="用户名">
                                  <el-input placeholder="请输入用户名" v-model="user.username"></el-input>
                              </el-form-item>
                              <el-form-item label="密码">
                                  <el-input @keydown.enter="login" placeholder="请输入密码" type="password" v-model="user.password"></el-input>
                              </el-form-item>
                              <el-form-item>
                                  <el-button type="success" style="width:100%" @click="login">登录</el-button>
                              </el-form-item>
                          </el-form>
                          <div style="text-align: center;color: #666;font-size: 14px;padding: 10px 0;">
                              (体验账号:tom 密码:123456)<span style="margin-left: 45px;color: #666" >没有账号？</span><span @click="router.push('/singLn')" style="cursor: pointer;color: #79bbff">去注册</span>
                          </div>
                      </el-tab-pane>
                      <el-tab-pane label="手机验证登录" name="second" >
                          <h3 style="text-align: center;">手机验证登录</h3>
                          <el-form :model="phoneLoginForm" label-position="top" :rules="phoneLoginFormRules">
                              <el-form-item prop="phone" label="手机号">
                                  <el-input placeholder="手机号" clearable prefix-icon="el-icon-phone" v-model="phoneLoginForm.phone">
                                  </el-input>
                              </el-form-item>
                              <el-form-item prop="phoneCode" label="验证码">
                                  <el-input placeholder="验证码" prefix-icon="el-icon-key" v-model="phoneLoginForm.phoneCode">
                                      <template #append>
                                          <el-button @click="sendVerificationCode" :disabled="!show">
                                              <span v-if="show">获取验证码</span>
                                              <span v-else>{{ timeCount }}s后重试</span>
                                          </el-button>
                                      </template>
                                  </el-input>
                              </el-form-item>
                              <el-form-item>
                                  <el-button type="success" style="width:100%" @click="phoneLogin">登录</el-button>
                              </el-form-item>
                          </el-form>
                          <div style="text-align: center;color: #666;font-size: 14px;padding: 10px 0;">
                              (体验账号:tom 密码:123456)<span style="margin-left: 45px;color: #666" >没有账号？</span><span @click="router.push('/singLn')" style="cursor: pointer;color: #79bbff">去注册</span>
                          </div>
                      </el-tab-pane>
                  </el-tabs>

              </div>
          </div>

      </div>

  </div>
</template>

<script setup>
import {ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router";


// 定义登录模式
const activeName = ref('first');

// 手机登录数据
const phoneLoginForm = ref({phone: '', phoneCode: ''});
// 倒计时的显示
const show = ref(true);
const timeCount = ref(60);
const code = ref('');

const userLoginPhone=ref({});
// 发送验证码
const sendVerificationCode = () => {
  if (!phoneLoginForm.value.phone) {
    ElMessage.error('请输入手机号');
    return;
  }
  // 模拟发送验证码
  // https://www.idmayi.com/sendcode/index
  // 模拟60s倒计时
  // setTimeout(() => {
  //   show.value = !show.value;
  // }, 60000);
  const phone =  phoneLoginForm.value.phone;
  axios.post(BASE_URL+'/v1/user/getVerificationCode/'+phone).then((response)=>{
    if (response.data.code === 2000){
      ElMessage.success('验证码已发送，请查收');
      // 弹出弹窗，显示此次登录的验证码  response.dada.dada
      // 设置验证码显示5秒后消失
      // 设置验证码显示5秒后消失
      ElMessage({
        message: '验证码：' + response.data.data.code,
        type: 'warning',
        duration: 10000 // 10秒后自动消失
      });
      //ElMessage.info('验证码：'+response.data.data);
      // 保存数据验证码，用于验证
      code.value = response.data.data.code;
      // 用户信息
      userLoginPhone.value =response.data.data;
      // 开始倒计时
      show.value = false;
      const timer = setInterval(() => {
        if (timeCount.value > 0) {
          timeCount.value--;
        } else {
          show.value = true;
          clearInterval(timer);
        }
      }, 1000);
    }else {
      ElMessage.error(response.data.msg);
    }
  })

};

// 手机登录
const phoneLogin = () => {
  // 如果输入内容为空。提示
  if (!phoneLoginForm.value.phone || !phoneLoginForm.value.phoneCode) {
    ElMessage.error('请输入手机号和验证码');
    return;
  }
  if (phoneLoginForm.value.phoneCode===code.value){
    ElMessage.success('登录成功');
    // 跳转页面
    const user=userLoginPhone.value;
    localStorage.setItem('user',JSON.stringify(user));
    //4.登录成功后,跳转至HomeView,再重定向到用户列表页
    //const user=response.data.data;
    if(user.role==0){
      // 管理员
      router.push('/user');
      // 员工
    }else if(user.role==2){
      router.push('/empHome');
    }else if(user.role==1){
      // 客户
      router.push('/userHome');
    }

  }else {
    ElMessage.error('验证码错误');
  }
};

// 手机号验证规则
// 手机登录表单验证规则
const phoneLoginFormRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  phoneCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度为6位', trigger: 'blur' }
  ]
};




const user = ref({username: '', password: ''});
const login = () => {
  //console.log(user.value);
  //1.给后端发送登录请求,需要借助axios工具，注意：axios需要安装并导入！
  axios.post(BASE_URL+'/v1/user/login',user.value)
      .then((response)=>{
        //2.发送请求后，服务器处理完毕会给客户端响应结果，前端需要在回调函数中处理这个响应结果
        //response是响应对象,我们可以从响应对象response的data中得到后端服务器的响应数据
        //console.log(response);
        console.log(response.data);//后端返回的JsonResult
        console.log(response.data.data);//JsonResult的data,这里是userVO
        //3.根据后端的响应结果做前端处理
        if(response.data.code == 2000){
          ElMessage.success('登录成功!');
          //6.登录成功后,将userVO存入localStorage中
          /* localStorage只能存储字符串类型的键值对!!! */
          localStorage.setItem('user',JSON.stringify(response.data.data));
          //4.登录成功后,跳转至HomeView,再重定向到用户列表页
          const user=response.data.data;
          if(user.role==0){
            // 管理员
            router.push('/user');
            // 员工
          }else if(user.role==2){
            router.push('/empHome');
          }else if(user.role==1){
            // 客户
            router.push('/userHome');
          }
          //router.push('/user');
        }else{
          ElMessage.error(response.data.msg);
          //5.登录失败,清空输入框
          user.value = {username: '', password: ''};
        }
      })
}
</script>

<style scoped>

</style>